from rest_framework.decorators import api_view, permission_classes, action
from rest_framework.response import Response
from rest_framework import status, viewsets
from rest_framework.permissions import AllowAny, IsAuthenticated, IsAdminUser
from rest_framework.authtoken.models import Token
from django.contrib.auth import logout
from django.contrib.auth.models import User
from django.db.models import Q
from django.utils import timezone
from .serializers import (
    LoginSerializer, UserSerializer, RoleSerializer, 
    UserProfileSerializer, UserManagementSerializer,
    SystemConfigSerializer, OperationLogSerializer
)
from .models import Role, UserProfile, SystemConfig, OperationLog
from .utils import log_operation


@api_view(['GET'])
@permission_classes([AllowAny])
def api_info(request):
    """API信息接口"""
    return Response({
        'message': '欢迎使用Django API',
        'version': '1.0.0',
        'status': 'running',
        'framework': 'Django + Vue + Element Plus'
    })


@api_view(['GET', 'POST'])
@permission_classes([AllowAny])
def hello(request):
    """示例接口"""
    if request.method == 'GET':
        return Response({
            'message': 'Hello from Django!',
            'method': 'GET'
        })
    elif request.method == 'POST':
        data = request.data
        return Response({
            'message': 'Data received!',
            'method': 'POST',
            'received_data': data
        }, status=status.HTTP_201_CREATED)


@api_view(['POST'])
@permission_classes([AllowAny])
def login(request):
    """管理员登录接口"""
    serializer = LoginSerializer(data=request.data)
    
    if serializer.is_valid():
        user = serializer.validated_data['user']
        
        # 检查是否是管理员或超级用户
        if not (user.is_staff or user.is_superuser):
            return Response({
                'error': '权限不足，只有管理员可以登录'
            }, status=status.HTTP_403_FORBIDDEN)
        
        # 获取或创建token
        token, created = Token.objects.get_or_create(user=user)
        
        # 序列化用户信息
        user_data = UserSerializer(user).data
        
        return Response({
            'token': token.key,
            'user': user_data,
            'message': '登录成功'
        }, status=status.HTTP_200_OK)
    
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def logout_view(request):
    """登出接口"""
    try:
        # 删除用户的token
        request.user.auth_token.delete()
        logout(request)
        return Response({
            'message': '登出成功'
        }, status=status.HTTP_200_OK)
    except Exception as e:
        return Response({
            'error': str(e)
        }, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def user_info(request):
    """获取当前用户信息"""
    from .permissions import get_user_permissions
    
    serializer = UserSerializer(request.user)
    user_data = serializer.data
    
    # 添加用户权限信息
    user_data['permissions'] = get_user_permissions(request.user)
    
    # 添加角色信息
    if hasattr(request.user, 'profile') and request.user.profile.role:
        user_data['role'] = {
            'id': request.user.profile.role.id,
            'name': request.user.profile.role.name
        }
    else:
        user_data['role'] = None
    
    return Response(user_data)


# ==================== 系统设置模块 ViewSets ====================

class UserManagementViewSet(viewsets.ModelViewSet):
    """用户管理ViewSet"""
    queryset = User.objects.all().select_related('profile').order_by('-date_joined')
    serializer_class = UserManagementSerializer
    permission_classes = [IsAuthenticated, IsAdminUser]
    
    def get_queryset(self):
        """支持搜索和筛选"""
        queryset = super().get_queryset()
        search = self.request.query_params.get('search', None)
        is_active = self.request.query_params.get('is_active', None)
        is_staff = self.request.query_params.get('is_staff', None)
        
        if search:
            queryset = queryset.filter(
                Q(username__icontains=search) | 
                Q(email__icontains=search) |
                Q(first_name__icontains=search) |
                Q(last_name__icontains=search)
            )
        
        # 只有明确传入'true'或'false'时才过滤
        if is_active and is_active in ['true', 'false']:
            queryset = queryset.filter(is_active=is_active == 'true')
        
        if is_staff and is_staff in ['true', 'false']:
            queryset = queryset.filter(is_staff=is_staff == 'true')
        
        return queryset
    
    def perform_create(self, serializer):
        """创建用户时记录日志"""
        user = serializer.save()
        log_operation(
            self.request.user, 'create', '用户管理', 
            f'创建用户: {user.username}', self.request
        )
    
    def perform_update(self, serializer):
        """更新用户时记录日志"""
        user = serializer.save()
        log_operation(
            self.request.user, 'update', '用户管理',
            f'更新用户: {user.username}', self.request
        )
    
    def perform_destroy(self, instance):
        """删除用户时记录日志"""
        username = instance.username
        instance.delete()
        log_operation(
            self.request.user, 'delete', '用户管理',
            f'删除用户: {username}', self.request
        )
    
    @action(detail=True, methods=['post'])
    def reset_password(self, request, pk=None):
        """重置用户密码"""
        user = self.get_object()
        new_password = request.data.get('password', '123456')
        user.set_password(new_password)
        user.save()
        
        log_operation(
            request.user, 'update', '用户管理',
            f'重置用户密码: {user.username}', request
        )
        
        return Response({'message': '密码重置成功'})
    
    @action(detail=True, methods=['post'])
    def toggle_status(self, request, pk=None):
        """切换用户启用/禁用状态"""
        user = self.get_object()
        user.is_active = not user.is_active
        user.save()
        
        status_text = '启用' if user.is_active else '禁用'
        log_operation(
            request.user, 'update', '用户管理',
            f'{status_text}用户: {user.username}', request
        )
        
        return Response({
            'message': f'用户已{status_text}',
            'is_active': user.is_active
        })


class RoleViewSet(viewsets.ModelViewSet):
    """角色管理ViewSet"""
    queryset = Role.objects.all()
    serializer_class = RoleSerializer
    permission_classes = [IsAuthenticated, IsAdminUser]
    
    def get_queryset(self):
        """支持搜索"""
        queryset = super().get_queryset()
        search = self.request.query_params.get('search', None)
        is_active = self.request.query_params.get('is_active', None)
        
        if search:
            queryset = queryset.filter(
                Q(name__icontains=search) | Q(description__icontains=search)
            )
        
        # 只有明确传入'true'或'false'时才过滤
        if is_active and is_active in ['true', 'false']:
            queryset = queryset.filter(is_active=is_active == 'true')
        
        return queryset
    
    def perform_create(self, serializer):
        """创建角色时记录日志"""
        role = serializer.save()
        log_operation(
            self.request.user, 'create', '角色管理',
            f'创建角色: {role.name}', self.request
        )
    
    def perform_update(self, serializer):
        """更新角色时记录日志"""
        role = serializer.save()
        log_operation(
            self.request.user, 'update', '角色管理',
            f'更新角色: {role.name}', self.request
        )
    
    def perform_destroy(self, instance):
        """删除角色时记录日志"""
        role_name = instance.name
        instance.delete()
        log_operation(
            self.request.user, 'delete', '角色管理',
            f'删除角色: {role_name}', self.request
        )


class SystemConfigViewSet(viewsets.ModelViewSet):
    """系统配置ViewSet"""
    queryset = SystemConfig.objects.all()
    serializer_class = SystemConfigSerializer
    permission_classes = [IsAuthenticated, IsAdminUser]
    
    def get_queryset(self):
        """支持按类型和搜索筛选"""
        queryset = super().get_queryset()
        config_type = self.request.query_params.get('config_type', None)
        search = self.request.query_params.get('search', None)
        
        if config_type:
            queryset = queryset.filter(config_type=config_type)
        
        if search:
            queryset = queryset.filter(
                Q(key__icontains=search) | 
                Q(description__icontains=search)
            )
        
        return queryset
    
    def perform_create(self, serializer):
        """创建配置时记录日志"""
        config = serializer.save()
        log_operation(
            self.request.user, 'create', '系统配置',
            f'创建配置: {config.key}', self.request
        )
    
    def perform_update(self, serializer):
        """更新配置时记录日志"""
        config = serializer.save()
        log_operation(
            self.request.user, 'update', '系统配置',
            f'更新配置: {config.key}', self.request
        )
    
    def perform_destroy(self, instance):
        """删除配置时记录日志"""
        config_key = instance.key
        instance.delete()
        log_operation(
            self.request.user, 'delete', '系统配置',
            f'删除配置: {config_key}', self.request
        )
    
    @action(detail=False, methods=['get'])
    def types(self, request):
        """获取所有配置类型"""
        types = SystemConfig.CONFIG_TYPES
        return Response([{'value': t[0], 'label': t[1]} for t in types])


class OperationLogViewSet(viewsets.ReadOnlyModelViewSet):
    """操作日志ViewSet（只读）"""
    queryset = OperationLog.objects.all()
    serializer_class = OperationLogSerializer
    permission_classes = [IsAuthenticated, IsAdminUser]
    
    def get_queryset(self):
        """支持按时间、用户、类型筛选"""
        queryset = super().get_queryset()
        
        # 时间范围筛选
        start_date = self.request.query_params.get('start_date', None)
        end_date = self.request.query_params.get('end_date', None)
        
        if start_date:
            queryset = queryset.filter(created_at__gte=start_date)
        if end_date:
            queryset = queryset.filter(created_at__lte=end_date)
        
        # 用户筛选
        username = self.request.query_params.get('username', None)
        if username:
            queryset = queryset.filter(username__icontains=username)
        
        # 操作类型筛选
        log_type = self.request.query_params.get('log_type', None)
        if log_type:
            queryset = queryset.filter(log_type=log_type)
        
        # 模块筛选
        module = self.request.query_params.get('module', None)
        if module:
            queryset = queryset.filter(module__icontains=module)
        
        # 搜索
        search = self.request.query_params.get('search', None)
        if search:
            queryset = queryset.filter(
                Q(username__icontains=search) |
                Q(action__icontains=search) |
                Q(module__icontains=search)
            )
        
        return queryset
    
    @action(detail=False, methods=['get'])
    def types(self, request):
        """获取所有日志类型"""
        types = OperationLog.LOG_TYPES
        return Response([{'value': t[0], 'label': t[1]} for t in types])
    
    @action(detail=False, methods=['get'])
    def stats(self, request):
        """获取日志统计信息"""
        total = self.get_queryset().count()
        today = self.get_queryset().filter(
            created_at__date=timezone.now().date()
        ).count()
        
        # 按类型统计
        type_stats = {}
        for log_type, label in OperationLog.LOG_TYPES:
            count = self.get_queryset().filter(log_type=log_type).count()
            type_stats[log_type] = {'label': label, 'count': count}
        
        return Response({
            'total': total,
            'today': today,
            'by_type': type_stats
        })
